package com.scisoft.scan.control.returngoods;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.PartBean;
import com.scisoft.scan.data.returngoods.ReturnGoodsDetailBean;
import com.scisoft.scan.data.returngoods.ReturnGoodsOrderBean;
import com.scisoft.scan.data.returngoods.ReturnGoodsReasonBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_ReturnGoods;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

public class ReturnGoodsDetailActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private ClearEditText et_bar;
    private ListView lv_data;
    private TextView bt_all;
    private TextView bt_undo;
    private TextView bt_done;
    private TextView tv_submit;
    private View v_all;
    private View v_undo;
    private View v_done;
    private List<ReturnGoodsDetailBean> returnGoodsDetailBeanList;
    private List<ReturnGoodsDetailBean> currentList;
    private String currentflag = "1";//1 全部 2 待处理 3 已处理
    private ReturnGoodsOrderBean orderBean;
    private ReturnGoodsDetailBean currentDetailBean;
    private String orderState;//0 未完成 1已完成
    private List<ReturnGoodsReasonBean> returnGoodsReasonBeanList;//退货原因列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//即隐藏标题栏
        setContentView(R.layout.activity_return_goods_detail);

        currentList = new ArrayList<>();
        returnGoodsDetailBeanList = new ArrayList<>();
        //参数传递
        Intent intent = getIntent();
        orderBean = (ReturnGoodsOrderBean) intent.getSerializableExtra("data");
        TextView tv_orderType = findViewById(R.id.tv_orderType);
        tv_orderType.setText(orderBean.orderType);
        TextView tv_title = findViewById(R.id.tv_title);
        tv_title.setText(orderBean.customerName);
        TextView tv_orderNo = findViewById(R.id.tv_orderNo);
        tv_orderNo.setText(orderBean.orderNo);
        TextView tv_depotName = findViewById(R.id.tv_depotName);
        tv_depotName.setText(orderBean.depotName);
        //初始化扫码
        init();
        //控件初始化
        et_bar = findViewById(R.id.et_bar);
        lv_data = findViewById(R.id.lv_data);
        lv_data.setOnItemClickListener(new ListViewClick());
        tv_submit = findViewById(R.id.tv_submit);
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtil.showPress(ReturnGoodsDetailActivity.this);
                CompletePartOrderTask completePartOrderTask = new CompletePartOrderTask(ReturnGoodsDetailActivity.this);
                completePartOrderTask.execute();
            }
        });
        orderState = orderBean.orderState;
        if ("1".equals(orderState)) {
            tv_submit.setVisibility(View.INVISIBLE);
        } else {
            tv_submit.setVisibility(View.VISIBLE);
        }
        bt_all = findViewById(R.id.bt_all);
        bt_undo = findViewById(R.id.bt_undo);
        bt_done = findViewById(R.id.bt_done);
        v_all = findViewById(R.id.v_all);
        v_undo = findViewById(R.id.v_undo);
        v_done = findViewById(R.id.v_done);
        //页签切换
        bt_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
                BindData(ReturnGoodsDetailActivity.this);
            }
        });
        bt_undo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
                BindData(ReturnGoodsDetailActivity.this);
            }
        });
        bt_done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
                BindData(ReturnGoodsDetailActivity.this);
            }
        });
        setButton(bt_all);

        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        QueryDepotOrder();
    }

    //编辑
    private class ListViewClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position >= 0 && position < currentList.size()) {
                ReturnGoodsDetailBean returnGoodsDetailBean = currentList.get(position);
                alert_edit(returnGoodsDetailBean);
            }
        }
    }

    //弹窗编辑
    private void alert_edit(final ReturnGoodsDetailBean returnGoodsDetailBean) {
        //1.创建一个Dialog对象,去除标题栏
        final Dialog mDialog = new Dialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局,将自定义布局设置进去
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_returngoods, null);
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);

        //4、设置点击其它地方不让消失弹窗
        mDialog.setCancelable(false);
        //5、初始化控件
        //下拉列表
        final List<String> reasonList = new ArrayList<>();
        for (int i = 0; i < returnGoodsReasonBeanList.size(); i++) {
            reasonList.add(returnGoodsReasonBeanList.get(i).ReasonName);
        }
        final Spinner spin_reason = dialogView.findViewById(R.id.spin_reason);
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.style_spinner, reasonList);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_reason.setAdapter(adapter1);
        //总数
        TextView tv_zms = dialogView.findViewById(R.id.tv_zms);
        tv_zms.setText(String.valueOf(returnGoodsDetailBean.partCount));
        //修改的数量
        final TextView et_count = dialogView.findViewById(R.id.et_count);
        TextView tv_equal = dialogView.findViewById(R.id.tv_equal);
        //按钮
        tv_equal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //全部退货
                et_count.setText(String.valueOf(returnGoodsDetailBean.partCount));
                ReturnGoodsDetailBean newData = returnGoodsDetailBean;
                newData.returnCount = et_count.getText().toString();
                ReturnPart(newData);
                mDialog.dismiss();
            }
        });
        TextView tv_none = (TextView) dialogView.findViewById(R.id.tv_none);
        tv_none.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //清零
                et_count.setText("0");
            }
        });
        TextView tv_ok = (TextView) dialogView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按下确定键后的事件
                ReturnGoodsDetailBean newData = returnGoodsDetailBean;
                newData.returnCount = et_count.getText().toString();
                int position = spin_reason.getSelectedItemPosition();
                newData.reason = returnGoodsReasonBeanList.get(position).ReasonName;
                newData.reasonCode = returnGoodsReasonBeanList.get(position).ReasonCode;
                ReturnPart(newData);
                mDialog.dismiss();
            }
        });
        TextView tv_cancel = (TextView) dialogView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    //设置tab页的颜色
    private void setButton(View v) {
        if (v.getId() == bt_all.getId()) {
            currentflag = "1";
            v_all.setVisibility(View.VISIBLE);
            v_undo.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else if (v.getId() == bt_undo.getId()) {
            currentflag = "2";
            v_all.setVisibility(View.INVISIBLE);
            v_undo.setVisibility(View.VISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else {
            currentflag = "3";
            v_all.setVisibility(View.INVISIBLE);
            v_undo.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.VISIBLE);
            bt_all.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_select));
        }
    }

    //绑定数据
    private void BindData(Context context) {
        //判断当前页签
        currentList.clear();
        if (currentflag.equals("1")) {
            for (int i = 0; i < returnGoodsDetailBeanList.size(); i++) {
                currentList.add(returnGoodsDetailBeanList.get(i));
            }
        } else if (currentflag.equals("2")) {
            for (int i = 0; i < returnGoodsDetailBeanList.size(); i++) {
                ReturnGoodsDetailBean temp = returnGoodsDetailBeanList.get(i);
                if (temp.ifOk.equals("0")) {
                    currentList.add(temp);
                }
            }
        } else {
            for (int i = 0; i < returnGoodsDetailBeanList.size(); i++) {
                ReturnGoodsDetailBean temp = returnGoodsDetailBeanList.get(i);
                if (temp.ifOk.equals("1")) {
                    currentList.add(temp);
                }
            }
        }
        int undo = 0;
        for (int i = 0; i < returnGoodsDetailBeanList.size(); i++) {
            ReturnGoodsDetailBean temp = returnGoodsDetailBeanList.get(i);
            if (temp.ifOk.equals("0")) {
                undo++;
            }
        }
        int done = returnGoodsDetailBeanList.size() - undo;
        //更新标题
        bt_all.setText("全部[" + returnGoodsDetailBeanList.size() + "]");
        bt_undo.setText("待处理[" + undo + "]");
        bt_done.setText("已处理[" + done + "]");
        //更新数据
        ReturnGoodsDetailAdapter adapter = new ReturnGoodsDetailAdapter(currentList, context);
        lv_data.setAdapter(adapter);
    }

    //查询订单明细
    private void QueryDepotOrder() {
        CommonUtil.showPress(this);
        QueryOrderDetailTask queryOrderDetailTask = new QueryOrderDetailTask(ReturnGoodsDetailActivity.this);
        queryOrderDetailTask.execute();
    }

    //匹配唯一码
    private void filterData(PartBean partBean) {
        for (int i = 0; i < returnGoodsDetailBeanList.size(); i++) {
            ReturnGoodsDetailBean depotOrderDetailBean = returnGoodsDetailBeanList.get(i);
            if (depotOrderDetailBean.serialNo != null && depotOrderDetailBean.partCode != null && depotOrderDetailBean.supplierCode != null) {
                if ("0".equals(depotOrderDetailBean.ifOk)) {
                    //只有未处理的才弹出来
                    if (depotOrderDetailBean.partCode.equals(partBean.partCode) && depotOrderDetailBean.supplierCode.equals(partBean.supplierCode)
                            && depotOrderDetailBean.serialNo.equals(partBean.serialNo)) {
                        //只有有码件才匹配，匹配规则：配件代码、供应商代码、唯一码完全一致
                        alert_edit(depotOrderDetailBean);
                        break;
                    }
                }

            }
        }
    }

    //配件退货提交
    private void ReturnPart(ReturnGoodsDetailBean returnGoodsDetailBean) {
        CommonUtil.showPress(this);
        ReturnPartTask returnPartTask = new ReturnPartTask(ReturnGoodsDetailActivity.this, returnGoodsDetailBean);
        returnPartTask.execute();
    }

    //查询订单明细服务
    class QueryOrderDetailTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryOrderDetailTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                returnGoodsDetailBeanList = WebServiceHelper_ReturnGoods.RETURNGOODS_03(orderBean.orderId, orderBean.depotId, orderBean.depotAreaId);
                returnGoodsReasonBeanList = WebServiceHelper_ReturnGoods.RETURNGOODS_06();
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //全部拣货提交服务
    class ReturnPartTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        ReturnGoodsDetailBean mreturnGoodsDetailBean;
        private String msg = "";

        ReturnPartTask(Context context, ReturnGoodsDetailBean returnGoodsDetailBean) {
            super();
            mcontext = context;
            mreturnGoodsDetailBean = returnGoodsDetailBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_ReturnGoods.RETURNGOODS_04(orderBean.orderId, mreturnGoodsDetailBean,orderBean.depotAreaId);
                if (msg.contains("成功")) {
                    returnGoodsDetailBeanList = WebServiceHelper_ReturnGoods.RETURNGOODS_03(orderBean.orderId, orderBean.depotId,orderBean.depotAreaId);
                    msg = "成功";
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //全部拣货提交服务
    class CompletePartOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        CompletePartOrderTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_ReturnGoods.RETURNGOODS_05(orderBean.orderId);

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    class ReturnGoodsDetailAdapter extends BaseAdapter {
        private List<ReturnGoodsDetailBean> returnGoodsDetailBeanList;//数据源
        private LayoutInflater mInflater;//布局装载器对象
        private Context mContext;

        public ReturnGoodsDetailAdapter(List<ReturnGoodsDetailBean> returnGoodsDetailBeanList, Context context) {
            this.returnGoodsDetailBeanList = returnGoodsDetailBeanList;
            mInflater = LayoutInflater.from(context);
            mContext = context;
        }

        @Override
        public int getCount() {
            //return返回的是int类型，也就是页面要显示的数量。
            return returnGoodsDetailBeanList.size();
        }

        @Override
        public Object getItem(int position) {
            return returnGoodsDetailBeanList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //将布局文件转化为View对象
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_returngoodsdetail, null);
            }
            //数量
            TextView tv_partCount = convertView.findViewById(R.id.tv_partCount);
            //已拣
            TextView tv_doneCount = convertView.findViewById(R.id.tv_doneCount);
            //待拣
            TextView tv_todoCount = convertView.findViewById(R.id.tv_todoCount);
            //完成
            TextView tv_ok = convertView.findViewById(R.id.tv_ok);
            //图片
            ImageView iv_img = convertView.findViewById(R.id.iv_img);
            //配件信息
            TextView tv_partInfo = convertView.findViewById(R.id.tv_partInfo);
            //供应商信息
            TextView tv_supplierInfo = convertView.findViewById(R.id.tv_supplierInfo);
            //唯一码信息
            TextView tv_serialNo = convertView.findViewById(R.id.tv_serialNo);


            //获取相应索引的ItemBean对象
            ReturnGoodsDetailBean bean = returnGoodsDetailBeanList.get(position);
            tv_partCount.setText(String.valueOf(bean.partCount));
            tv_doneCount.setText(String.valueOf(bean.returnCount));
            tv_todoCount.setText(String.valueOf(bean.notReturnCount));
            tv_partInfo.setText(bean.partCode + " " + bean.partName);
            tv_supplierInfo.setText(bean.supplierCode + " " + bean.supplierName);

            if ("1".equals(bean.ifOk)) {
                tv_ok.setVisibility(View.VISIBLE);
            } else {
                tv_ok.setVisibility(View.GONE);
            }

            //判断是否有码
            if (bean.serialNo != null && bean.serialNo != "") {
                tv_serialNo.setText("有码件   " + bean.serialNo);
            } else {
                tv_serialNo.setText("无码件");
            }

            if (bean.imgUrl != null && !bean.imgUrl.equals("")) {
                Picasso.with(mContext).load(bean.imgUrl).into(iv_img);
            } else {
                iv_img.setImageDrawable(convertView.getResources().getDrawable(R.drawable.ic_noimage));
            }
            return convertView;
        }
    }

    //region 以下为扫码相关

    //初始化
    private void init() {
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (barCodeBean.barType == BarCodeBean.BAR_PART) {
                    PartBean partBean = barCodeBean.partBean;
                    if (partBean == null) {
                        Toast.makeText(ReturnGoodsDetailActivity.this, "无效条码：" + barCode, Toast.LENGTH_LONG).show();
                    } else {
                        filterData(partBean);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "无效配件条码", Toast.LENGTH_LONG).show();
                }

            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(ReturnGoodsDetailActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    et_bar.setText(decodedData);
                    ScanData(decodedData);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(ReturnGoodsDetailActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };
    //endregion
}
